package com.smedi.ismedi.database.starter.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.smedi.ismedi.authority.starter.util.AuthorityUtil;
import com.smedi.ismedi.database.starter.property.SqlPermissionProperty;
import com.smedi.ismedi.database.starter.util.ReflectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;

/**
 * 数据库初始化操作
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MyBatisMetaHandler implements MetaObjectHandler {
    private final SqlPermissionProperty sqlPermissionProperty;

    private final AuthorityUtil authorityUtil;

    private final static Long nobody = -1L;

    private final static Long unCaughtBody = -99L;

    // 获取当前操作人员
    private Long getOperator()  {
        return authorityUtil.getLoginAccess().getPersonId();
    }

    /**
     * 新增数据执行
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 创建时间
        this.setFieldValByName("createdDate", LocalDateTime.now(), metaObject);
        // 更新时间
        this.setFieldValByName("latestUpdatedDate", LocalDateTime.now(), metaObject);
        // 版本
        this.setFieldValByName("version", 0, metaObject);
        // 软删除标记
        this.setFieldValByName("isDeleted", false, metaObject);

        Long personId = nobody;
        if (sqlPermissionProperty.isEnableAuthor()) {
            try {
                personId = getOperator();
            } catch (Exception e) {
                personId = unCaughtBody;
                log.error("保存时出现错误，请联系系统管理员！, trace: {}", e.getStackTrace());
            }
        }

        // 创建人
        this.setFieldValByName("createdUserId", personId, metaObject);
        // 更新人
        this.setFieldValByName("latestUpdatedUserId", personId, metaObject);
    }

    /**
     * 更新数据执行
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("latestUpdatedDate", LocalDateTime.now(), metaObject);

        Long personId = nobody;
        if (sqlPermissionProperty.isEnableAuthor()) {
            try {
                personId = getOperator();
            } catch (Exception e) {
                personId = unCaughtBody;
                log.error("更新时出现错误，请联系系统管理员！, trace: {}", e.getStackTrace());
            }
        }

        // 更新人
        this.setFieldValByName("latestUpdatedUserId", personId, metaObject);
    }
}
